const app = getApp()
// 外部引入
import {
  CstopBluetoothDevicesDiscovery,
  CcreateBLEConnection,
  openBlue,
  startBluetoothDevicesDiscovery,
  getBluetoothAdapterState
} from "../../request/blue"
// 引入防抖函数
import debounce from "../../utils/debounce"
Page({
  data: {
    searching: false, // 搜素标志位
    devicesList: [], // 设备列表
    deviceId: "", // 设备ID
    deviceName: "", // 设备名称
    layerModel: false, // 弹窗显示
    isLocation: false, // 是否打开定位
    isopenGPS: false // 是否打开gps
  },
  // 清除蓝牙绑定功能函数
  clearBlue() {
    try {
      // 清除所有存储信息
      wx.clearStorageSync()
    } catch (error) {
      console.log(error);
    }
  },

  Search: debounce(async function () {
    var that = this
    // 获取存储得设备id和设备名称
    that.data.deviceId = wx.getStorageSync('deviceId')
    that.data.deviceName = wx.getStorageSync('deviceName')
    that.checkLocation() // 检查定位权限和定位功能是否打开
    let res = {} // 初始化设备返回结果
    // 如果未绑定蓝牙
    if (!that.data.searching && that.data.isLocation && that.data.isopenGPS) {
      // 开启蓝牙适配器
      res = await openBlue()
      console.log('蓝牙初始化成功', res);
      // 获取蓝牙适配器状态
      res = await getBluetoothAdapterState()
      console.log('获得蓝牙适配器状态', res);
      // 开始搜索蓝牙
      res = await startBluetoothDevicesDiscovery()
      console.log('开始搜索蓝牙', res);
      // 如果开始搜索则开启loading并清空设备列表
      if (res.errno == 0 || errCode == 0) {
        this.setData({
          searching: true,
          devicesList: []
        })
      }
    } else {
      wx.showToast({
        title: '请检查定位和蓝牙是否开启',
      })
      // 停止搜索蓝牙
      res = await CstopBluetoothDevicesDiscovery()
      this.setData({
        searching: false
      })
    }
  }, 500, {
    leading: true,
    trailing: false
  }),
  // 连接指定蓝牙功能函数
  Connect: debounce(async function (e) {
    var that = this
    var advertisData, name
    // 将点击的设备名和ID进行存储
    for (var i = 0; i < that.data.devicesList.length; i++) {
      if (e.currentTarget.id == that.data.devicesList[i].deviceId) {
        name = that.data.devicesList[i].name
        advertisData = that.data.devicesList[i].advertisData
      }
    }
    try {
      let res = await CstopBluetoothDevicesDiscovery()
      console.log('关闭结果', res);
      if (res.errno === 0) {
        that.setData({
          searching: false
        })
      }
      res = await CcreateBLEConnection(e.currentTarget.id, name)
      console.log(res);
      // 如果连接成功
      if (res.errno == 0 || res.errCode == 0) {
        // 对设备ID和设备名称进行存储
        wx.setStorageSync('deviceId', e.currentTarget.id)
        wx.setStorageSync('deviceName', name)
        wx.showToast({
          title: '连接蓝牙成功',
          icon: "success",
          duration: 1000
        })
        wx.navigateTo({
          url: '../control/control?connectedDeviceId=' + e.currentTarget.id + '&name=' + name
        })
      } else {
        // 连接失败
        wx.showModal({
          title: '提示',
          content: '连接失败',
          showCancel: false
        })
      }
    } catch (error) {
      console.log(error);
    }
  }, 500, {
    leading: true,
    trailing: false
  }),
  checkOpenGPS() {
    var that=this
    that.setData({
      isopenGPS: app.globalData.SystemInfo.locationEnabled
    })
    // 检查gps功能
    if (!that.data.isopenGPS) {
      wx.showToast({
        title: '请打开定位GPS后重新进入',
        icon: "error"
      })
    }


  },
  // 检查是否授权地理位置
  checkLocation() {
    var that = this
    // 获取用户设置
    wx.getSetting({
      success: res => {
        console.log("location", res.authSetting['scope.userLocation']);
        // 如果用户未授权定位
        if (!res.authSetting['scope.userLocation']) {
          // 授权定位信息
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.setData({
                layerModel: true
              })
              // 授权成功提示信息
              wx.showToast({
                title: '授权成功',
                duration: 1000
              })
            },
            fail() {
              wx.showToast({
                title: '授权失败,请授权后进入',
                icon: "error",
                duration: 1000
              })
              that.setData({
                layerModel: true
              })
            }
          })
        } else {
          that.setData({
            isLocation: true
          })
        }
      }
    })
    console.log("gps", that.data.isopenGPS);
    console.log("location", that.data.isLocation);
  },
  changeModalCancel(e) {
    var that = this
    if (e.currentTarget.dataset.cancel) {
      that.setData({
        layerModel: false
      })
    }
    console.log('取消回调');
  },
  onShow: function (options) {
    var that = this
    that.checkOpenGPS() // 检查是否打开地理位置
    that.checkLocation() // 检查定位权限
    // 设置设备列表高度
    var list_height = ((app.globalData.SystemInfo.windowHeight - 50) * (700 / app.globalData.SystemInfo.windowWidth)) - 60
    that.setData({
      list_height: list_height
    })

    wx.onBluetoothAdapterStateChange(function (res) {
      that.setData({
        searching: res.discovering
      })
      if (!res.available) {
        that.setData({
          searching: false
        })
      }
    })
    wx.onBluetoothDeviceFound(function (devices) {
      //剔除重复设备，过滤名字是否为 Ai-Thinker 
      var isnotexist = true
      if (devices.deviceId) {
        if (devices.advertisData) {
          devices.advertisData = app.buf2hex(devices.advertisData)
        } else {
          devices.advertisData = ''
        }
        // console.log(devices)x
        for (var i = 0; i < that.data.devicesList.length; i++) {
          if (devices.deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist && devices[0].name != '') {
          that.data.devicesList.push(devices[0])
        }
      } else if (devices.devices) {
        if (devices.devices[0].advertisData) {
          devices.devices[0].advertisData = app.buf2hex(devices.devices[0].advertisData)
        } else {
          devices.devices[0].advertisData = ''
        }
        // console.log(devices.devices[0])
        for (var i = 0; i < that.data.devicesList.length; i++) {
          if (devices.devices[0].deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist && devices.devices[0].name != '') {
          that.data.devicesList.push(devices.devices[0])
        }
      } else if (devices[0]) {
        if (devices[0].advertisData) {
          devices[0].advertisData = app.buf2hex(devices[0].advertisData)
        } else {
          devices[0].advertisData = ''
        }
        // console.log(devices[0])
        for (var i = 0; i < devices_list.length; i++) {
          if (devices[0].deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist && devices[0].name != '') {
          that.data.devicesList.push(devices[0])
        }
      }
      that.setData({
        devicesList: that.data.devicesList
      })
    })
  },
  onHide: async function () {
    var that = this
    that.setData({
      devicesList: []
    })
    if (this.data.searching) {
      let res = await CstopBluetoothDevicesDiscovery()
      if (res.errno == 0 || res.errCode == 0) {
        that.setData({
          searching: false
        })
      }
    }
  }
})
   // 如果设备绑定过
    // if (that.data.deviceId && that.data.deviceName) {
    //   // 关闭蓝牙适配器进行重置
    //   wx.closeBluetoothAdapter({
    //     complete(res) {
    //       console.log('重置蓝牙成功');
    //       // 打开蓝牙适配器
    //       wx.openBluetoothAdapter({
    //         success(res) {
    //           console.log('打开蓝牙适配器成功');
    //           // 获取蓝牙适配器状态
    //           wx.getBluetoothAdapterState({
    //             success(result) {
    //               // 建立蓝牙连接
    //               that.createBLUEConnection(that.data.deviceId, that.data.deviceName)
    //               that.setData({
    //                 // 关闭搜索状态
    //                 searching: false,
    //                 // 重置设备列表
    //                 devicesList: []
    //               })
    //             },
    //           })
    //         }
    //       })
    //     }
    //   })
    //   // 连接成功不继续执行函数
    //   return
    // }